<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <!-- 修正的视口配置 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <meta name="theme-color" content="#2196F3">
    <title>HTML加载渲染器</title>
    <script>
        // 增强的CORS代理列表（优先级排序）
        const PROXY_SERVERS = [
            "https://api.allorigins.win/raw?url=",
            "https://corsproxy.io/?",
            "https://api.codetabs.com/v1/proxy/?quest=",
            "https://thingproxy.freeboard.io/fetch/",
            "https://yacdn.org/proxy/"
        ];

        // 设备检测和适配
        const deviceInfo = (() => {
            const ua = navigator.userAgent;
            return {
                isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua),
                isTablet: /iPad|Android|Tablet/i.test(ua),
                isIOS: /iPhone|iPad|iPod/i.test(ua),
                isAndroid: /Android/i.test(ua),
                dpr: window.devicePixelRatio || 1,
                isLowEnd: /(Android|iPhone|iPad).*AppleWebKit(?!.*Chrome)/i.test(ua),
                screenWidth: Math.min(window.screen.width, window.screen.height)
            };
        })();

        // 性能优化：防抖调整UI大小
        let resizeTimeout;
        function adjustUISizes() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
                // 动态计算基础字体大小
                let baseSize = 14;
                if (deviceInfo.screenWidth <= 320) {
                    baseSize = 12;
                } else if (deviceInfo.screenWidth <= 414) {
                    baseSize = 14;
                } else {
                    baseSize = 16;
                }
                
                // 限制最大缩放为2倍
                const scaleFactor = Math.min(deviceInfo.dpr, 2);
                document.documentElement.style.fontSize = `${baseSize * scaleFactor}px`;
                
                // 移动设备特定调整
                if (deviceInfo.isMobile) {
                    const statusEl = document.getElementById('status');
                    if (statusEl) {
                        statusEl.style.padding = deviceInfo.screenWidth <= 360 ? '10px 8px' : '15px 10px';
                        const progressContainer = document.querySelector('.progress-container');
                        if (progressContainer) {
                            progressContainer.style.width = deviceInfo.screenWidth <= 320 ? '85%' : '90%';
                            progressContainer.style.height = '0.35rem';
                        }
                    }
                }
            }, 100);
        }

        // 增强的fetchWithRetry函数
        async function fetchWithRetry(url, retries = PROXY_SERVERS.length) {
            let lastError;
            
            for (let i = 0; i < retries; i++) {
                const proxy = PROXY_SERVERS[i % PROXY_SERVERS.length];
                try {
                    updateStatus(`尝试连接服务器 (${new URL(proxy).hostname})...`, 20 + (i * 10));
                    
                    const proxyUrl = proxy + encodeURIComponent(url);
                    const controller = new AbortController();
                    const timeout = deviceInfo.isLowEnd ? 20000 : 15000;
                    const timeoutId = setTimeout(() => controller.abort(), timeout);
                    
                    const response = await fetch(proxyUrl, {
                        signal: controller.signal,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    });
                    clearTimeout(timeoutId);
                    
                    if (!response.ok) {
                        throw new Error(`服务器响应异常: ${response.status}`);
                    }
                    
                    const contentLength = response.headers.get('content-length');
                    if (contentLength && parseInt(contentLength) > 3 * 1024 * 1024) {
                        throw new Error('文件过大(超过3MB)');
                    }
                    
                    return await response.text();
                } catch (error) {
                    lastError = error;
                    console.warn(`代理尝试 ${i+1} 失败:`, error);
                    
                    // 指数退避重试
                    const delay = Math.min(1000, 200 * Math.pow(2, i));
                    await new Promise(resolve => setTimeout(resolve, delay));
                    continue;
                }
            }
            throw lastError || new Error("所有代理服务器均不可用");
        }

        // 优化的状态更新函数
        function updateStatus(message, progress = null) {
            const statusEl = document.getElementById('status');
            if (!statusEl) return;
            
            const progressBar = document.getElementById('progress-bar');
            const statusText = document.getElementById('status-text');
            const loader = document.getElementById('loader');
            
            // 使用requestAnimationFrame优化性能
            requestAnimationFrame(() => {
                if (statusText) statusText.textContent = message;
                
                if (progress !== null && progressBar) {
                    progressBar.style.width = `${progress}%`;
                    progressBar.setAttribute('aria-valuenow', progress);
                }
                
                if (loader) {
                    if (progress === 100) {
                        loader.style.display = 'none';
                        loader.className = 'icon-check';
                    } else {
                        loader.style.display = 'inline-block';
                        loader.className = 'loader';
                    }
                }
            });
        }

        // 主渲染函数 - 移动设备优化版
        async function renderContent() {
            adjustUISizes();
            updateStatus("正在初始化渲染器...", 10);
            
            try {
                // 目标URL
                const targetUrl = "https://gitee.com/KingDove/KingDoveRead/raw/master/index.html";
                
                // 获取HTML内容
                updateStatus("正在下载内容...", 20);
                const html = await fetchWithRetry(targetUrl);
                updateStatus("内容下载完成，正在解析...", 60);
                
                // 模拟解析过程
                await new Promise(resolve => setTimeout(resolve, deviceInfo.isMobile ? 800 : 300));
                updateStatus("准备渲染内容...", 80);
                
                // 创建渲染容器
                const container = document.createElement('div');
                container.id = 'rendered-content';
                
                // 移动设备特定样式
                const containerStyles = {
                    position: 'fixed',
                    top: '0',
                    left: '0',
                    width: '100%',
                    height: '100%',
                    border: 'none',
                    opacity: '0',
                    transition: 'opacity 0.5s ease-in-out',
                    zIndex: '1',
                    overflow: 'auto',
                    '-webkit-overflow-scrolling': 'touch'
                };
                
                // 应用样式
                Object.assign(container.style, containerStyles);
                
                // 使用iframe安全渲染
                const iframe = document.createElement('iframe');
                iframe.srcdoc = html;
                
                // iframe样式
                const iframeStyles = {
                    width: '100%',
                    height: '100%',
                    border: 'none',
                    display: 'block',
                    'min-height': deviceInfo.isMobile ? '100vh' : '100%'
                };
                
                // 应用iframe样式
                Object.assign(iframe.style, iframeStyles);
                
                // iOS特定修复
                if (deviceInfo.isIOS) {
                    iframe.style.webkitOverflowScrolling = 'touch';
                    container.style.webkitOverflowScrolling = 'touch';
                }
                
                // 清空并渲染
                document.body.innerHTML = '';
                container.appendChild(iframe);
                document.body.appendChild(container);
                
                // 显示淡入效果
                setTimeout(() => {
                    container.style.opacity = '1';
                    updateStatus("渲染完成!", 100);
                    
                    // 延迟隐藏状态提示
                    setTimeout(() => {
                        const statusEl = document.getElementById('status');
                        if (statusEl) {
                            statusEl.style.opacity = '0';
                            setTimeout(() => {
                                statusEl.remove();
                                // iOS键盘处理
                                if (deviceInfo.isIOS && 'virtualKeyboard' in navigator) {
                                    setTimeout(() => {
                                        navigator.virtualKeyboard.show();
                                    }, 300);
                                }
                                window.focus();
                            }, 500);
                        }
                    }, 1000);
                }, 150);
                
            } catch (error) {
                console.error("渲染失败:", error);
                showErrorUI(error);
            }
        }

        // 增强的错误处理UI - 移动设备优化
        function showErrorUI(error) {
            updateStatus(`加载失败: ${getUserFriendlyError(error)}`, 100);
            const statusEl = document.getElementById('status');
            if (!statusEl) return;
            
            const errorDetails = document.createElement('div');
            errorDetails.className = 'error-details';
            
            // 根据错误类型提供特定建议
            const errorType = classifyError(error);
            let suggestion = '';
            
            switch(errorType) {
                case 'network':
                    suggestion = '网络连接失败，请检查网络';
                    break;
                case 'size':
                    suggestion = '文件过大，请使用WiFi网络';
                    break;
                case 'proxy':
                    suggestion = '代理服务不可用，请稍后再试';
                    break;
                default:
                    suggestion = '发生错误，请尝试刷新';
            }
            
            errorDetails.innerHTML = `
                <div class="error-message">${suggestion}</div>
                <button class="retry-btn" onclick="location.reload()">
                    <span class="icon-repeat"></span> 重试
                </button>
                <div class="manual-option">
                    <p>或者尝试手动访问:</p>
                    <a href="https://gitee.com/KingDove/KingDoveRead/raw/master/index.html" target="_blank" class="manual-link">
                        <span class="icon-link"></span> 原始链接
                    </a>
                </div>
                ${deviceInfo.isMobile ? '<div class="mobile-tip">提示: 在移动设备上建议使用WiFi网络</div>' : ''}
                ${deviceInfo.isLowEnd ? '<div class="low-end-tip">检测到您的设备性能较低，加载可能需要更长时间</div>' : ''}
            `;
            
            statusEl.appendChild(errorDetails);
            
            // 错误分析
            if (errorType === 'network') {
                setTimeout(() => {
                    const tip = document.createElement('div');
                    tip.className = 'network-tip';
                    tip.textContent = deviceInfo.isMobile ? '请检查移动数据/WiFi是否开启' : '请检查网络连接';
                    errorDetails.appendChild(tip);
                }, 300);
            }
        }

        // 错误分类函数
        function classifyError(error) {
            if (!error) return 'unknown';
            
            const message = error.message || '';
            if (message.includes('Failed to fetch') || message.includes('NetworkError')) {
                return 'network';
            }
            if (message.includes('文件过大')) {
                return 'size';
            }
            if (message.includes('代理') || message.includes('CORS')) {
                return 'proxy';
            }
            return 'unknown';
        }

        // 用户友好的错误信息
        function getUserFriendlyError(error) {
            if (!error) return '未知错误';
            
            const type = classifyError(error);
            switch(type) {
                case 'network': return '网络连接失败';
                case 'size': return '文件大小超过限制';
                case 'proxy': return '代理服务不可用';
                default: return error.message || '未知错误';
            }
        }

        // 页面加载后执行（添加延迟以等待CSS加载）
        window.addEventListener('load', () => {
            // 移动设备增加额外延迟
            const delay = deviceInfo.isMobile ? 100 : 50;
            setTimeout(renderContent, delay);
        });
        
        // 使用防抖的resize事件
        window.addEventListener('resize', adjustUISizes);
        
        // 防止双击缩放和长按菜单（移动设备）
        if (deviceInfo.isMobile) {
            document.addEventListener('dblclick', (e) => {
                e.preventDefault();
            }, { passive: false });
            
            document.addEventListener('contextmenu', (e) => {
                e.preventDefault();
            }, { passive: false });
        }
        
        // iOS键盘弹出/收起事件处理
        if (deviceInfo.isIOS) {
            window.addEventListener('resize', () => {
                if (window.visualViewport) {
                    const viewport = window.visualViewport;
                    const statusEl = document.getElementById('status');
                    if (statusEl) {
                        statusEl.style.bottom = `${viewport.height - window.innerHeight}px`;
                    }
                }
            });
        }
    </script>
    <style>
        /* 优化后的基础样式 - 移动设备优先 */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
            -webkit-text-size-adjust: none;
        }
        
        html {
            -webkit-text-size-adjust: 100%;
            -ms-text-size-adjust: 100%;
            text-rendering: optimizeLegibility;
            -webkit-font-smoothing: antialiased;
            height: 100%;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 
                         Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif;
            line-height: 1.5;
            overflow-x: hidden;
            touch-action: manipulation;
            background-color: #f5f5f5;
            min-height: 100vh;
            min-height: -webkit-fill-available; /* 针对移动浏览器视口高度问题 */
        }
        
        /* 优化的状态提示框 - 移动设备优先 */
        #status {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            padding: 1rem;
            background: rgba(255, 255, 255, 0.98);
            color: #333;
            text-align: center;
            z-index: 9999;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            backdrop-filter: blur(5px);
            -webkit-backdrop-filter: blur(5px);
            will-change: transform, opacity;
            box-sizing: border-box;
        }
        
        /* 响应式设计优化 - 小屏幕设备 */
        @media (max-width: 414px) {
            #status {
                padding: 0.8rem;
            }
            
            #status-text {
                font-size: 0.9rem;
                margin-bottom: 0.4rem;
            }
            
            .retry-btn {
                padding: 0.6rem 1rem;
                font-size: 0.85rem;
            }
            
            .error-message {
                font-size: 0.85rem;
                margin-bottom: 0.6rem;
            }
            
            .manual-option {
                font-size: 0.8rem;
            }
        }
        
        /* 极窄设备适配 (iPhone 5/SE等) */
        @media (max-width: 320px) {
            #status {
                padding: 0.6rem;
            }
            
            #status-text {
                font-size: 0.8rem;
            }
            
            .progress-container {
                height: 0.3rem;
                margin: 0.5rem 0;
            }
            
            .loader {
                width: 1rem;
                height: 1rem;
                margin: 0.5rem 0;
            }
            
            .retry-btn {
                padding: 0.5rem 0.8rem;
                font-size: 0.8rem;
            }
            
            .error-message {
                font-size: 0.8rem;
            }
            
            .mobile-tip, .low-end-tip {
                font-size: 0.7rem;
                padding: 0.3rem;
            }
        }
        
        /* 横屏模式优化 */
        @media (orientation: landscape) {
            #status {
                padding: 0.6rem;
            }
            
            @media (max-height: 500px) {
                #status {
                    flex-direction: row;
                    flex-wrap: wrap;
                    justify-content: center;
                    padding: 0.4rem;
                }
                
                #status-text {
                    width: 100%;
                    margin-bottom: 0.3rem;
                    font-size: 0.85rem;
                }
                
                .progress-container {
                    width: 60%;
                    margin: 0.2rem;
                    height: 0.3rem;
                }
                
                .loader {
                    margin: 0.2rem;
                    width: 1rem;
                    height: 1rem;
                }
            }
        }
        
        /* 进度条样式优化 */
        .progress-container {
            width: 85%;
            max-width: 25rem;
            height: 0.35rem;
            background: rgba(0, 0, 0, 0.1);
            border-radius: 0.2rem;
            margin: 0.8rem 0;
            overflow: hidden;
            position: relative;
        }
        
        #progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
            border-radius: 0.2rem;
            transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            width: 0%;
            position: relative;
            overflow: hidden;
            will-change: width;
        }
        
        #progress-bar::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(
                90deg,
                transparent,
                rgba(255, 255, 255, 0.3),
                transparent
            );
            animation: shimmer 1.5s infinite;
        }
        
        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }
        
        /* 状态文本优化 */
        #status-text {
            font-size: 0.95rem;
            font-weight: 500;
            margin-bottom: 0.5rem;
            max-width: 95%;
            word-break: break-word;
            will-change: contents;
        }
        
        /* 加载动画优化 - 移动设备性能考虑 */
        .loader {
            display: inline-block;
            width: 1.1rem;
            height: 1.1rem;
            border: 0.15rem solid rgba(33, 150, 243, 0.3);
            border-radius: 50%;
            border-top-color: #2196F3;
            animation: spin 1s linear infinite;
            margin: 0.7rem 0;
            will-change: transform;
            animation-timing-function: linear;
        }
        
        .icon-check {
            display: inline-block;
            color: #4CAF50;
            font-size: 1.1rem;
            margin: 0.7rem 0;
            animation: bounce 0.5s;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        @keyframes bounce {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }
        
        /* 错误状态样式优化 */
        .error-details {
            margin-top: 0.8rem;
            animation: fadeIn 0.5s ease;
            width: 100%;
            max-width: 25rem;
        }
        
        .error-message {
            color: #f44336;
            margin-bottom: 0.7rem;
            font-weight: 500;
            font-size: 0.9rem;
        }
        
        .retry-btn {
            padding: 0.65rem 1.1rem;
            background: linear-gradient(135deg, #2196F3 0%, #21CBF3 100%);
            color: white;
            border: none;
            border-radius: 0.3rem;
            cursor: pointer;
            font-size: 0.9rem;
            display: inline-flex;
            align-items: center;
            transition: all 0.2s;
            box-shadow: 0 2px 4px rgba(33, 150, 243, 0.3);
            will-change: transform;
            -webkit-appearance: none;
        }
        
        .retry-btn:active {
            transform: translateY(1px);
            box-shadow: 0 1px 2px rgba(33, 150, 243, 0.3);
        }
        
        .manual-option {
            margin-top: 0.8rem;
            font-size: 0.85rem;
            color: #666;
        }
        
        .manual-link {
            color: #2196F3;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            margin-top: 0.4rem;
            word-break: break-all;
            transition: color 0.2s;
            font-size: 0.85rem;
        }
        
        .manual-link:active {
            color: #0d8bf2;
        }
        
        /* 图标样式优化 */
        .icon-repeat, .icon-link, .icon-check {
            display: inline-flex;
            margin-right: 0.4rem;
            align-items: center;
            justify-content: center;
        }
        
        .icon-repeat::after {
            content: "↻";
            font-size: 0.9em;
        }
        
        .icon-link::after {
            content: "🔗";
            font-size: 0.85em;
        }
        
        .icon-check::after {
            content: "✓";
        }
        
        /* 动画效果优化 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(8px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* 设备特定提示优化 */
        .mobile-tip {
            margin-top: 0.8rem;
            font-size: 0.75rem;
            color: #ff9800;
            background: rgba(255, 152, 0, 0.1);
            padding: 0.4rem;
            border-radius: 0.25rem;
        }
        
        .low-end-tip {
            margin-top: 0.7rem;
            font-size: 0.7rem;
            color: #9e9e9e;
            background: rgba(158, 158, 158, 0.1);
            padding: 0.35rem;
            border-radius: 0.25rem;
        }
        
        .network-tip {
            margin-top: 0.4rem;
            font-size: 0.75rem;
            color: #f44336;
            animation: fadeIn 0.5s ease;
        }
        
        /* 高DPI设备优化 */
        @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
            .loader {
                border-width: 0.18rem;
            }
        }
        
        /* iOS特定修复 */
        @supports (-webkit-touch-callout: none) {
            body {
                /* iOS视口高度修复 */
                min-height: -webkit-fill-available;
                height: -webkit-fill-available;
            }
            
            .retry-btn {
                -webkit-appearance: none;
                border-radius: 0.3rem;
            }
        }
        
        /* 安卓特定修复 */
        @media (-android-min-device-pixel-ratio:0) {
            .progress-container {
                height: 0.4rem;
            }
        }
        
        /* 深色模式支持 */
        @media (prefers-color-scheme: dark) {
            body {
                background-color: #121212;
            }
            
            #status {
                background: rgba(30, 30, 30, 0.98);
                color: #f5f5f5;
            }
            
            .progress-container {
                background: rgba(255, 255, 255, 0.1);
            }
            
            .manual-option {
                color: #b0b0b0;
            }
            
            .mobile-tip {
                background: rgba(255, 152, 0, 0.2);
            }
        }
    </style>
</head>
<body>
    <div id="status">
        <div id="status-text">正在准备加载内容...</div>
        <div class="progress-container">
            <div id="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"></div>
        </div>
        <div class="loader" id="loader"></div>
    </div>
</body>
</html>
